<template>
  <div class="fullMain">
    <x-header :left-options="{backText: '',showBack: false}"
      :right-options="{showMore: true}" @on-click-more="showMenusOfActionsOnAnnouncement = true">
      {{pageTitle}}
      <div v-transfer-dom>
        <alert v-model="isShowAlert"> {{alertText}}</alert>
      </div>
    </x-header>
    <div style="height:20px"/>
    <div v-transfer-dom>
      <actionsheet :menus="actionsOnAnnouncement"
                   @on-click-menu="selectActionOnAnnouncement"
                   v-model="showMenusOfActionsOnAnnouncement" show-cancel></actionsheet>
    </div>
    <div class="mainbBg">
      <div style="text-align:center">
        <label style="font-size:17px; font-weight:bold">公告内容</label><br>
      </div>

      <group>
        <x-textarea :max="maxLengthOfContent" :placeholder="contentPlaceholder" 
        v-model="noticeContent" :autosize="true"
        ></x-textarea>
        <x-switch title="置顶该公告" :value-map="[false, true]" v-model="isFirst" ></x-switch>
      </group>

      <div style="height: 40px" />
      <div class="click_btn">
        <button class="my_button" @click="back()">返回
        </button>
        <button class="my_button" @click="submit()">{{submitButton}}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
  import {XHeader, Cell, Group, Confirm, Checklist, XSwitch, XTextarea, Actionsheet} from 'vux'
  import {XInput, XButton} from 'vux'
  import {PopupPicker} from 'vux'
  import {mapState} from 'Vuex'
  import group from 'api/group'
  import notice from 'api/notice'

  export default {
    name: 'G_group_announcement_create_and_modify',
    data () {
      return {
        pageTitle: '新建群公告',
        submitButton: '发布',

        alertText: "",
        isShowAlert: false,

        isModify: false, // 不是创建就是修改公告

        isFirst: false,   //是否置顶该公告
        contentPlaceholder: '请输入公告内容...',
        maxLengthOfContent: 80,
        noticeContent: '',//公告内容

        showMenusOfActionsOnAnnouncement: false,
        actionsOnAnnouncement: {
          'delete': '删除该公告'
        },

        //为了可以刷新绑定值，一个无意义的数据项（但是有用）
        refresh: ['firstElement'],
      }
    },
    computed: {
      ...mapState(['groupPresent', 'announcementSelected']),
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
    },
    mounted () {
      this.init();
      this.cleanPage();
    },
    watch: {
    },
    components: {
      XHeader,
      XInput,
      PopupPicker,
      Group,
      Confirm,
      XButton,
      XSwitch,
      XTextarea,
      Actionsheet
    },
    methods: {
      init () {
        // 如果store中的announcement为空
        if (JSON.stringify(this.announcementSelected) === "{}") {
          this.isModify = false;
          this.cleanPage();
        } else {
          console.log(this.announcementSelected)
          this.isModify = true;
          this.pageTitle = '修改群公告';
          this.submitButton = '修改并发布';
          this.noticeContent = this.announcementSelected.massage;
          this.isFirst = this.announcementSelected.isFirst;
          this.$set(); // 虽然加上这行代码运行会报错，但是可以解决x-textarea无法数据绑定的问题，报的错误也无关痛痒，不影响使用（应该）
        }
      },
      cleanPage () {
        this.noticeContent = "";
      },
      selectActionOnAnnouncement (value) {
        if ('delete' === value) {
          this.deleteAnnoucement();
        }
      },
      back () {
        this.$router.go(-1)
      },
      showAlert (alertText) {
        this.isShowAlert = true
        this.alertText = alertText
      },
      closeTip () {
        this.isShowAlert = false
        this.alertText = ''
      },
      async deleteAnnoucement () {
        if (this.announcementSelected.issuerId !== this.userInfo.userId) {
          this.showAlert("仅发布人可删除此公告");
          return;
        } else {
          const result = await notice.deleteNotice(this.announcementSelected.noticeId);
          if (result.code === 1) {
            this.showAlert("公告删除成功");
            setTimeout(() => {
              this.back();
            }, 1500);
          } else {
            this.showAlert("删除失败，请稍后再试");
          }
        }
      },
      async submit () {
        let reg = /^[ ]*$/;
        if (reg.test(this.noticeContent)) {
          this.cleanPage();
          this.showAlert('公告内容不可为空');
          return;
        }

        let codeOfResult = 0;
        let messageToShow = '';
        if (!this.isModify) {
          const resultOfCreate = await notice.addNotice({
            groupId: this.groupPresent.groupId,
            isFirst: this.isFirst,
            message: this.noticeContent
          });
          codeOfResult = resultOfCreate.code;
          messageToShow = '发布';
        } else {
          if (this.userInfo.userId !== this.announcementSelected.issuerId) {
            this.showAlert("仅发布人可修改此公告");
            return;
          } else {
            const resultOfModify = await notice.updateNotice({
              detail: {
                dateTime: '',
                isFirst: this.isFirst,
                issuerId: this.announcementSelected.issuerId,
                massage: this.noticeContent,
                readNum: 0
              },
              groupId: this.groupPresent.groupId,
              noticeId: this.announcementSelected.noticeId
            });
            codeOfResult = resultOfModify.code;
            messageToShow = '修改';
          }
        }
        if (codeOfResult === 1) {
          this.showAlert('公告' + messageToShow + '成功');
          setTimeout(() => {
            this.closeTip();
            this.back();
          }, 1800);
        } else {
          this.showAlert(messageToShow + '操作失败，请稍后再试');
          setTimeout(() => {
            this.closeTip();
          }, 1500);
        }
      }
    }
  }
</script>
<style scoped>
  .click_btn {
    height: 40px;
    width: 80%;
    margin: 3px auto;
    display: flex;
    justify-content: space-around;
  }

  .my_button {
    width: 120px;
    height: 40px;
    border: none;
    color: white;
    background: #1abc9c;
    text-align: center;
    outline: none;
    border-radius: 5px;
    margin-left: 15px;
  }

  #checkBox input {
    color: white;
    background: #1abc9c;
    border: none;
    border-radius: 3px;
    margin: auto 10px;
    /* padding:5px; */
  }

  #checkBox {
    border: #ececec dashed 1px;
    border-radius: 5px;
    padding: 10px;
    margin-top: 8px;
    margin-bottom: 8px;
  }
</style>